package com.bclz.netty.start;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;


public class NettyServerHandle extends ChannelInboundHandlerAdapter {



    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("["+ctx.channel().remoteAddress()+"] already connect... ");

        //ctx.channel().eventLoop().submit(()->{});     //异步提交任务,耗时较长可以使用这种提交任务方式

//        ctx.channel().eventLoop().scheduleAtFixedRate(()->{//定时调度任务
//            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("发送心跳...",CharsetUtil.UTF_8));
//        },2,3, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("READ THREAD："+Thread.currentThread().getName()+"**"+Thread.currentThread().getId());
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline();
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("["+channel.remoteAddress()+"]："+byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("already review data !!!!嘻嘻",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("SERVER HANDLE EXCEPTION！！！");
        ctx.close();
    }
}
